<template>
    <div style="padding-left: 20px; padding-right: 20px; padding-top: 20px">
        <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
                <header-toolbar :buttons="headerButtons" @delete="handleDelete" @refresh="handleRefresh"
                    @save="handleSave" :objectId.sync="receipt.id" @submit="handleSubmit" @back="handleReturnList"
                    @approve="handleApprove" @print="handlePrint" @unsubmit="handleUnSubmit"
                    @pushButtonClick="handlePushClick" :status.sync="receipt.status">
                    <template v-slot:pushButton>
                        <el-dropdown-item command="pushAccountsPayable" icon="el-icon-download">应收款</el-dropdown-item>
                    </template>
                </header-toolbar>
            </div>
            <div class="text item">
                <el-form :model="receipt" :rules="headerRules" ref="receiptForm" label-width="100px"
                    label-position="rigth">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="单据编号" prop="number">
                                <el-input v-model="receipt.number" disabled
                                    :placeholder="receipt.id ? '' : '保存后自动生成'"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="供应商" prop="status">
                                <supplier-select v-model="receipt.supplierId" @change="handleSupplierChange"
                                    :disabled="readonly">
                                </supplier-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="日期" prop="date">
                                <el-date-picker v-model="receipt.date" type="date" placeholder="选择日期"
                                    :disabled="readonly">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>

                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="币别" prop="currencyId">
                                <currency-select v-model="receipt.currencyId" placeholder="请选择币别" :disabled="readonly"
                                    @change="handleChangeCurrency">
                                </currency-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="汇率" prop="exchangeRate">
                                <number-input v-model="receipt.exchangeRate" :precision="6" :min="0"
                                    controls-position="right" style="width: 100%;" :disabled="readonly"
                                    @change="handleChangeExchangeRate"></number-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="部门" prop="departmentId">
                                <department-select v-model="receipt.departmentId"
                                    @change="() => receipt.purchaserId = null" :disabled="readonly">
                                </department-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="采购员" prop="purchaserId">
                                <employee-select v-model="receipt.purchaserId" :departmentId.sync="receipt.departmentId"
                                    :disabled.sync="!receipt.departmentId" :disabled="readonly">
                                </employee-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="含税" prop="includeTax">
                                <el-checkbox v-model="receipt.includeTax" :disabled="readonly"
                                    @change="handleChangeIncludeTax">
                                </el-checkbox>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="合计金额" prop="totalAmountFr">
                                <el-input v-model="receipt.totalAmountFr" disabled>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="备注" prop="comment">
                                <el-input v-model="receipt.comment" :disabled="readonly"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="单据状态" prop="status">
                                <status-label :status.sync="receipt.status">
                                </status-label>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </el-card>
        <el-divider></el-divider>
        <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
                <body-toolbar :table="$refs.xTable" @add="handleAddItem" @delete="handleBodyDelete" @fill="handleFill"
                    :status.sync="receipt.status"></body-toolbar>
            </div>
            <div class="text item">
                <vxe-table border align="center" show-footer :data="receipt.items" auto-resize :export-config="{}"
                    resizable ref="xTable" :show-overflow="true" @cell-click="handleCellClick" size="small"
                    :edit-rules="bodyRules" :mouse-config="{ selected: true }" :checkbox-config="{ range: true }"
                    :keyboard-config="{
                        isArrow: true,
                        isDel: false,
                        isEnter: true,
                        isTab: true,
                        isEdit: true,
                    }" :edit-config="{
                        trigger: 'click',
                        mode: 'cell',
                        activeMethod: handleCellEnableEdit,
                    }" :footer-method="handleFooterData" :merge-footer-items="mergeFooterItems">
                    <vxe-table-column type="checkbox" width="40" fixed="left"></vxe-table-column>
                    <vxe-table-column type="seq" width="40" fixed="left"></vxe-table-column>
                    <vxe-table-column field="productCode" title="产品代码" align="left" header-align="center" width="120"
                        fixed="left" :edit-render="{
                            attrs: {},
                            enabled: !this.readonly,
                        }">
                        <template #default="{ row }">
                            <div>
                                {{ row.productCode }}
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <product-select v-model="row.productId"
                                @change="(product) => handleChangeProduct(row, product)"></product-select>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="productName" title="产品名称" align="left" header-align="center" width="140"
                        fixed="left">
                        <template #default="{ row }">
                            <div>
                                {{ row.productName }}
                            </div>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="productModel" title="规格型号" align="left" header-align="center" width="120"
                        fixed="left">
                        <template #default="{ row }">
                            <div>
                                {{ row.productModel }}
                            </div>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="remark" title="备注" align="left" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                            enabled: !this.readonly,
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.remark }}</span>
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <el-input v-model="row.remark"></el-input>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="isGift" title="赠品" align="left" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                            enabled: !this.readonly,
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.isGift ? "是" : "" }}</span>
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <el-select v-model="row.isGift">
                                <el-option :value="true" label="是"></el-option>
                                <el-option :value="false" label="否"></el-option>
                            </el-select>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="purchaseUnitId" title="采购单位" align="center" header-align="center"
                        width="120" :edit-render="{
                            attrs: {},
                            autofocus: '.custom-input',
                            enabled: !this.readonly,
                        }">
                        <template #default="{ row }">
                            <div>
                                {{ row.purchaseUnitName }}
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <unit-select v-model="row.purchaseUnitId"
                                @change="(unit) => handleUnitChange(row, unit)"></unit-select>
                        </template>
                    </vxe-table-column>

                    <vxe-table-column field="purchaseQuantity" title="采购数量" align="right" header-align="center"
                        width="120" :edit-render="{
                            attrs: {},
                            autofocus: '.custom-input',
                            enabled: !this.readonly,
                        }">
                        <template #default="{ row }">
                            <div>
                                {{ row.purchaseQuantity }}
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <number-input v-model="row.purchaseQuantity" :precision="4"
                                optionClass="vxe-table–ignore-clear"
                                @input="(quantity) => handleQuanityChange(row, quantity)"></number-input>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="basicUnitId" title="计价单位" align="center" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                            autofocus: '.custom-input',
                            enabled: false,
                        }">
                        <template #default="{ row }">
                            <div>
                                {{ row.basicUnitName }}
                            </div>
                        </template>
                    </vxe-table-column>

                    <vxe-table-column field="basicQuantity" title="计价数量" align="right" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                            autofocus: '.custom-input',
                            enabled: false,
                        }">
                        <template #default="{ row }">
                            <div>
                                {{ row.basicQuantity }}
                            </div>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="price" title="单价" align="right" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                            enabled: !this.readonly,
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.price }}</span>
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <number-input v-model="row.price" :precision="4" :min="0"
                                @input="(price) => handleChangePrice(row, price)"></number-input>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="taxRateId" title="税率" align="left" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.taxRateName }}</span>
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <taxrate-select v-model="row.taxRateId"
                                @change="(taxRate) => handleChangeTaxRate(row, taxRate)"></taxrate-select>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="priceIncludeTax" title="含税单价" align="right" header-align="center"
                        width="120" :edit-render="{
                            attrs: {},
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.priceIncludeTax }}</span>
                            </div>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="priceExcludeTax" title="不含税单价" align="right" header-align="center"
                        width="120" :edit-render="{
                            attrs: {},
                            enabled: false
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.priceExcludeTax | money }}</span>
                            </div>
                        </template>
                    </vxe-table-column>

                    <vxe-table-column field="amountFr" title="不含税金额" align="right" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                            enabled: false
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.amountFr | money }}</span>
                            </div>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="amountFr" title="税额" align="right" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                            enabled: false
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.taxAmountFr | money }}</span>
                            </div>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="amountFr" title="价税合计" align="right" header-align="center" width="120"
                        :edit-render="{
                            attrs: {},
                            enabled: false
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.totalAmountFr | money }}</span>
                            </div>
                        </template>
                    </vxe-table-column>
                </vxe-table>
            </div>
        </el-card>
        <el-drawer direction="rtl" :visible.sync="editAttachmentDrawer" :with-header="false">
            <div v-if="editAttachmentDrawer">
                <attachment-panel :moduleCode="'purchaseReceipt'" :ownerId="receipt.id"></attachment-panel>
            </div>
        </el-drawer>
        <print-dialog ref="printPanel" :moduleCode="'purchaseReceipt'" :ids="[this.id]"></print-dialog>
    </div>
</template>
<script>
import {
    getPurchaseReceipt,
    addPurchaseReceipt,
    updatePurchaseReceipt,
    deletePurchaseReceipt,
    updatePurchaseReceiptStatus
} from "@/api/inventory/purchaseReceipt";

import { getProductPurchase } from "@/api/product"
import { calculateAmount, calculateBasicQuantity, setUnitConversionRate, setProductLatestPrice } from "@/utils/document"
import headerToolbar from "@/components/Bar/documentHeaderToolbar.vue";
import bodyToolbar from "@/components/Bar/documentBodyToolbar.vue";
import currencySelect from "@/components/Select/currencySelect.vue";
import departmentSelect from "@/components/Select/departmentSelect.vue";
import employeeSelect from "@/components/Select/employeeSelect.vue";
import supplierSelect from "@/components/Select/supplierSelect.vue";
import attachmentPanel from "@/components/Attachment/index.vue";
import printDialog from "@/components/Print/index.vue";
import unitSelect from "@/components/Select/unitSelect.vue";
import taxrateSelect from "@/components/Select/taxrateSelect.vue";
import numberInput from "@/components/Input/numberInput.vue";
import statusLabel from "@/components/Label/documentStatusLabel.vue";
import productSelect from "@/components/Select/productSelect.vue";
export default {
    components: {
        headerToolbar,
        bodyToolbar,
        currencySelect,
        departmentSelect,
        employeeSelect,
        unitSelect,
        supplierSelect,
        attachmentPanel,
        printDialog,
        taxrateSelect,
        numberInput,
        statusLabel,
        productSelect,
    },
    data() {
        return {
            receipt: {
                id: null,
                number: null,
                type: 1,
                supplierId: null,
                date: null,
                includeTax: true,
                currencyId: null,
                exchangeRate: null,
                totalAmountFr: null,
                comment: null,
                purchaserId: null,
                departmentId: null,
                status: 1,
                items: [],
                advancePaymentItems: []
            },
            headerRules: {
                date: [
                    {
                        required: true,
                        message: "请选择日期",
                        trigger: "change",
                    },
                ],
                type: [
                    {
                        required: true,
                        message: "请选择类型",
                        trigger: "change",
                    },
                ],
                supplierId: [
                    {
                        required: true,
                        message: "请选择供应商",
                        trigger: "change",
                    },
                ],
                currencyId: [
                    {
                        required: true,
                        message: "请选择币别",
                        trigger: "change",
                    },
                ],
                exchangeRate: [
                    {
                        required: true,
                        message: "请填写汇率",
                        trigger: "change",
                    },
                ]
            },
            bodyRules: {
                productId: [{ required: true, message: "请选择产品" }],
                purchaseUnitId: [{ required: true, message: "请填写采购单位" }],
                purchaseQuantity: [{ required: true, message: "请填写采购数量" }],
            },
            isModifying: false,
            mergeFooterItems: [{ row: 1, col: 2, rowspan: 1, colspan: 6 }],
            editAttachmentDrawer: false,
            currentCell: { row: null, column: null },
            quantityField: "purchaseQuantity",
            auxiliaryUnitField: "purchaseUnitId",
            headerButtons: ['save', 'submit', 'unsubmit', 'delete', 'back', 'approve', 'unapprove', 'print', 'push'],
            advanceButtons: ["add", "remove"],
            pickerOptions: {
                cellClassName: "vxe-table–ignore-clear"
            }
        };
    },
    methods: {
        getData() {
            if (!this.id) {
                this.setDefaultInfo();
                return;
            }
            getPurchaseReceipt(this.id).then((res) => {
                this.receipt = res || {};
            });
        },
        handleRefresh() {
            this.getData();
        },
        handleReturnList() {
            if (this.isModifying) {
                this.$confirm("当前数据为保存，是返回列表?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        this.$router.push({
                            name: "PurchaseReceipt",
                        });
                    })
                    .catch(() => { });
            } else {
                this.$router.push({
                    name: "PurchaseReceipt",
                });
            }
        },
        handleAddItem() {
            let item = this.getDefaultItemValue();

            this.$refs.xTable.insertAt(item, -1);
            this.order.items.push(item);
        },
        handleDelete({ id }) {
            deletePurchaseReceipt(id).then((res) => {
                this.$notify({
                    title: "成功",
                    message: "删除成功",
                    type: "success",
                    position: "bottom-right",
                });
                this.isModifying = false;
                this.handleReturnList();
            });
        },
        handleApprove(approved) {
            let status = approved ? 4 : 2;

            this.changeStatus(status)
        },
        handleSave() {
            this.validate(() => {
                this.saveData();
            })
        },
        handleSubmit() {
            this.changeStatus(3)
        },
        handleUnSubmit() {
            this.changeStatus(2)
        },
        async validate(callback) {
            const v1 = new Promise((resolve, reject) => {
                this.$refs.receiptForm.validate(valid => {
                    if (valid) resolve();
                }, true);
            });

            const v2 = new Promise((resolve, reject) => {
                this.$refs.xTable.validate(true, (errMap) => {
                    if (errMap) {
                        reject();
                    } else {
                        resolve();
                    }
                });
            });

            Promise.all([v1, v2]).then(() => {
                callback(true);
            });
        },
        saveData() {
            let items = this.getValidItems();

            this.receipt.items = items;
            if (this.id) {
                updatePurchaseReceipt(this.receipt).then((res) => {
                    if (res) {
                        this.receipt = res;
                        this.$notify({
                            title: "成功",
                            message: "保存成功",
                            type: "success",
                            position: "bottom-right",
                        });
                    }
                });
            } else {
                addPurchaseReceipt(this.receipt).then((res) => {
                    if (res) {
                        this.receipt = res;
                        this.$notify({
                            title: "成功",
                            message: "保存成功",
                            type: "success",
                            position: "bottom-right",
                        });
                    }
                });
            }
        },
        changeStatus(status) {
            updatePurchaseReceiptStatus(this.receipt.id, status).then(res => {
                let message = "";
                if (status == 3)
                    message = "提交成功";
                else if (status == 2 && this.receipt.status == 3)
                    message = "撤销提交成功";
                else if (status == 3 && this.receipt.status == 4)
                    message = "反审核成功";

                this.$notify({
                    title: "成功",
                    message: message,
                    type: "success",
                    position: "bottom-right",
                });
                this.getData();
            })
        },
        getValidItems() {
            let items = this.receipt.items.filter(x => x.productId);

            if (!items)
                return [];

            for (let i = 0; i < items.length; i++) {
                items[i].index = i + 1;
            }
            return items;
        },
        handleCellEnableEdit({ row, rowIndex, column, columnIndex }) {
            return true;
        },
        handleCellClick({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
            this.currentCell = { row: row, column: column }
        },
        getDefaultItemValue() {
            return {
                id: null,
                remark: null,
                productId: null,
                productCode: null,
                productName: null,
                purchaseUnitId: null,
                purchaseUnitName: null,
                purchaseQuantity: null,
                price: null,
                priceIncludeTax: null,
                priceExcludeTax: null,
                taxRateId: null,
                taxRateName: null,
                taxRateValue: null,
                basicUnitId: null,
                basicUnitName: null,
                basicQuantity: null,
            };
        },
        handleFooterData({ columns, data }) {
            let result = [];

            let subTotalRow = columns.map((column, _columnIndex) => {
                if (_columnIndex === 0) {
                    return "";
                }

                if (_columnIndex === 1) {
                    return "";
                }
                if (
                    ![
                        "amountFr",
                        "taxAmountFr",
                        "totalAmountFr"
                    ].includes(column.property)
                ) {
                    return "";
                }

                let total = 0;
                data.forEach((item) => {
                    if (item[column.property]) total = total + +item[column.property];
                });
                return total.toMoney();
            });

            result.push(subTotalRow);
            return result;
        },
        handleChangeProductType() {
            this.$confirm("更改类型会清空分录行，是否继续", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.order.items = [];
                })
                .catch(() => { });
        },
        handleChangeCurrency(currency) {
            this.order.currencyName = currency.currencyName;
            this.order.exchangeRate = currency.exchangeRate;
            let items = this.order.items;
            if (!items || items.length == 0)
                return;
            items.forEach(item => {
                calculateAmount(this.order.includeTax, this.order.exchangeRate, item, this.quantityField);
            })

        },
        handleChangeExchangeRate(item, value) {
            calculateAmount(this.order.includeTax, item.exchangeRate, item, this.quantityField);
        },
        handleChangeIncludeTax() {
            let items = this.order.items;
            if (!items || items.length == 0)
                return;
            items.forEach(item => {
                calculateAmount(this.order.includeTax, this.order.exchangeRate, item, this.quantityField);
            })
        },
        handleChangeProduct(item, product) {
            if (!product)
                return;
            item.productName = product.name;
            item.productCode = product.code;
            item.productModel = product.model;
            item.basicUnitId = product.basicUnitId;
            item.basicUnitName = product.basicUnitName;

            this.setProductDefaultInfo(item, product.id);
        },
        handleUnitChange(item, unit) {
            item.purchaseUnitName = unit.name;
        },
        handleSupplierChange(supplier) {
            this.receipt.supplierName = supplier.name;
        },
        handleQuanityChange(item, quantity) {
            calculateBasicQuantity(item, this.quantityField)
        },
        handleChangeTaxRate(item, taxRate) {
            item.taxRateName = taxRate.name;
            item.taxRateValue = taxRate.rate;
            calculateAmount(this.receipt.includeTax, item.exchangeRate, item, this.quantity);
        },
        handleChangePrice(item, price) {
            calculateAmount(this.receipt.includeTax, item.exchangeRate, item, this.quantity);
        },
        setDefaultInfo() {
            this.requisition.date = new Date();
            if (this.receipt.items && this.receipt.items.length > 0) return;
            //默认插四行数据
            for (let i = 0; i < 1; i++) {
                let item = this.getDefaultValueItem();
                this.order.items.push(item);
            }
        },
        handleAttachment() {
            this.editAttachmentDrawer = true;
        },
        handlePrint() {
            this.$refs.printPanel.showDialog();
        },
        handleBodyDelete({ ids, rows }) {
            if (rows.length == 0)
                return;

            let xids = rows.map((data) => {
                return data._XID;
            });

            this.receipt.items = this.receipt.items.filter((item) => {
                return xids.indexOf(item._XID) < 0
            })
        },
        handleFill() {
            if (!this.currentCell || !this.currentCell.row || this.receipt.items.length == 0)
                return;
            let row = this.currentCell.row;
            let column = this.currentCell.column;

            //有些字段不允许批量填充
            if (column.property == "productCode") {
                return;
            }

            this.order.items.forEach(item => {
                let columnNames = [column.property];

                if (column.property == "taxRateId") {
                    columnNames.push("taxRateName")
                }
                columnNames.forEach(columnName => {
                    item[columnName] = row[columnName];
                })

            })
        },
        setProductDefaultInfo(item, productId) {
            getProductPurchase(productId).then(res => {
                if (res) {
                    item.purchaseUnitId = res.purchaseUnitId;

                    if (item.purchaseUnitId) {
                        setUnitConversionRate(item, this.auxiliaryUnitField)
                    }

                    item.purchaseUnitName = res.purchaseUnitName;
                }
            });
        },
        handlePushClick(command) {
            if (command == "pushPurchaseReceipt")
                this.handlePushReceipt()


        },
        handlePushReceipt() {
            var id = this.order.id;

            if (!id)
                return;
            pushReceipt(id).then(res => {
                if (!res)
                    return;
                this.$notify({
                    title: "成功",
                    message: "下推成功",
                    type: "success",
                    position: "bottom-right",
                });
            })
        },
    },
    mounted() {
        this.$nextTick(() => {
            this.getData();
        });
    },
    computed: {
        id() {
            return this.$route.query.id;
        },
        readonly() {
            return this.receipt.status != 1 && this.receipt.status != 2;
        },
    },
    watch: {},
};
</script>
<style scoped></style>